﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Net.Mail;

namespace DATN.mds.MailManagement
{
    public partial class SendMailList : System.Web.UI.Page
    {
        SqlCommand cmd;
        SqlConnection cnn;
        protected string cnnString;
        int cus_id;
        

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindDrr();
                try
                {
                    //Kiem tra UserId
                    if (Session["Us_Id"] != null)
                    {
                        //Note Remind
                        Session["Remind"] = null;

                        //Kiem Tra Customer Id
                        if (Session["Cus_Id"] != null)
                        {
                            cus_id = Convert.ToInt16(Session["Cus_Id"].ToString());
                            Session.Contents.Remove("Cus_Id");
                            to_txt.Text = check_Mail(cus_id);
                            to_txt.Enabled = false;
                        }
                        else
                        {
                            // Label4.Text = "không Có session Cus_Id";
                        }

                        //Kiem tra Session Mail Từ Trend Suggestion
                        if (Session["SendAllMail"] != null && Session["AllIds"] != null)
                        {
                            string AllMail = Session["SendAllMail"].ToString();
                            Session.Contents.Remove("SendAllMail");
                            //Hiển thị lên phần gửi:
                            to_txt.Enabled = false;
                            to_txt.Text = AllMail;
                        }
                        else
                        {
                            // Label4.Text += "không Có session SendAllMail";
                        }
                    }
                    else
                    {
                        Response.Redirect("../Account/Login.aspx");
                    }
                }
                catch (Exception ex)
                {
                    Label4.Text = "Lỗi page load:" + ex;
                }
            }
        }

        protected void btAddContact_Click(object sender, EventArgs e)
        {
            if (ddr_GroupCS.SelectedValue != "-1")
            {
                CustomerId();
            }
        }

        //Tìm những Customer nào thuộc Group được select:
        protected void CustomerId()
        {
            try
            {
                cnnString = ConfigurationManager.ConnectionStrings["DATNconnection"].ToString();
                cnn = new SqlConnection(cnnString);
                cnn.Open();

                string SearchQuery = "SELECT * FROM dbo.GroupCs WHERE GrCus_Id = @GrCus_Id ";

                cmd = new SqlCommand(SearchQuery, cnn);

                cmd.Parameters.Add("@GrCus_Id", SqlDbType.Int);
                cmd.Parameters["@GrCus_Id"].Value = Convert.ToInt16(ddr_GroupCS.SelectedValue);

                SqlDataReader reader = cmd.ExecuteReader();

                string CkCusID = "";
                int i = 0;
                while (reader.Read())
                {
                    i++;
                    CkCusID += reader["Cus_Id"].ToString() + " ";
                    if (to_txt.Text != "" && to_txt.Text != null)
                    {
                        
                            to_txt.Text += CheckMailAddress(reader["Cus_Id"].ToString()) + ",";
                       
                    }
                    else
                    {
                            to_txt.Text += "," + CheckMailAddress(reader["Cus_Id"].ToString()) + ",";
                      
                    }
                }

                cnn.Close();
            }
            catch (Exception ex)
            {
                cnn.Close();
                Response.Write("Lỗi hiển thị: " + ex);
            }
            finally
            {
                cnn.Close();
            }
        }

        String mailx;
        //Lấy ra Mail Từ Cus ID
        protected string CheckMailAddress(string cus_id)
        {

            try
            {
                int id = Convert.ToInt16(cus_id);

                cnnString = ConfigurationManager.ConnectionStrings["DATNconnection"].ToString();
                cnn = new SqlConnection(cnnString);
                cnn.Open();

                String queryString = "SELECT * FROM [dbo].[Customers]  WHERE (([Cus_Id] = @Cus_Id))";
                cmd = new SqlCommand(queryString, cnn);
                cmd.Parameters.Add("@Cus_Id", SqlDbType.Int);
                cmd.Parameters["@Cus_Id"].Value = id;

                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    mailx = reader["Mail"].ToString();
                }

                cnn.Close();
            }
            catch (Exception ex)
            {
                Response.Write("Lỗi : "  + ex);
                cnn.Close();
            }

            return mailx;
        }


 
        //Button Gửi mail
        protected void Bt_SendMailOne(object sender, EventArgs e)
        {
            if (to_txt.Text != "" && to_txt.Text != null)
            {
                SendMail();
            }
            else {
                Label4.Text = "Nhập địa chỉ gửi Mail";
            }
        }

        //Gửi Mail
        public void SendMail()
        {
            try
            {
                if (Session["Us_Id"] != null)
                {
                    String UserName = chUserName(Convert.ToInt16(Session["Us_Id"].ToString()));

                    string a = to_txt.Text;
                    string[] words = a.Split(',');

                    MailMessage mail = new MailMessage();
                    SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

                    mail.From = new MailAddress("midasfpt@gmail.com", UserName);
                    mail.Subject = subject_txt.Text;
                    mail.Body = message_txt.Text;
                    for (int i = 0; i < (words.Length); i++)
                    {
                        if (i == 0)
                        {
                            if (words[i] != "")
                            {
                                mail.To.Add(words[i]);
                            }
                        }
                        else
                        {
                            if (i != (words.Length - 1))
                            {
                                if (words[i] != "")
                                {
                                    mail.Bcc.Add(words[i]);
                                }
                            }
                        }
                    }
                    SmtpServer.Port = 587;
                    SmtpServer.Credentials = new System.Net.NetworkCredential("midasfpt@gmail.com", "midas123$%^");
                    //you have to provide you gmail username and password
                    SmtpServer.EnableSsl = true;
                    SmtpServer.Send(mail);
                    Label4.Text = "Gửi Mail Thành Công.";
                }else {
                    Response.Redirect("../Account/Login.aspx");
                }
            }
            catch (Exception ex)
            {
                Label4.Text = "Gửi Mail lỗi: " + ex.Message + ex.ToString(); ;
            }
        }

        string  Rmail = "";
        //check mail ton tai:
        protected string check_Mail(int cus_id)
        {
            SqlDataReader rdr = null;
            try
            {
                string cnnString = ConfigurationManager.ConnectionStrings["DATNconnection"].ConnectionString;
                cnn = new SqlConnection(cnnString);
                cnn.Open();

                String queryString = "SELECT Mail FROM Customers WHERE Cus_Id = @Cus_Id";
                cmd = new SqlCommand(queryString, cnn);
                cmd.Parameters.Add("@Cus_Id", SqlDbType.Int);
                cmd.Parameters["@Cus_Id"].Value = cus_id;

                rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    // get the results of each column
                    Rmail = (string)rdr["Mail"];
                }
            }
            catch (Exception ex)
            {
                Label4.Text = " Lỗi ở Check Mail: " + ex;
            }
            return Rmail;
        }

        //Button bỏ qua
        protected void bt_Cancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("../mds.ContactManagement/IndexCM.aspx");
        }

        //Button Group Mail
        protected void bt_GroupMail_Click(object sender, EventArgs e)
        {
            Response.Redirect("../mds.MailManagement/GroupMail.aspx");
        }

        //Button Edit Template
        protected void bt_EditMailList_Click1(object sender, EventArgs e)
        {
            Response.Redirect("../mds.MailManagement/EditMailForm.aspx");
        }

        //Nhập Us_Id Trả ra Họ Và Tên
        string usname;
        protected string chUserName(int us_id)
        {
            usname = "";
            try
            {
                string cnnString = ConfigurationManager.ConnectionStrings["DATNconnection"].ConnectionString;
                cnn = new SqlConnection(cnnString);
                cnn.Open();

                String queryString = "SELECT * FROM Users WHERE Us_id = @Us_id";

                cmd = new SqlCommand(queryString, cnn);
                cmd.Parameters.Add("@Us_id", SqlDbType.VarChar);
                cmd.Parameters["@Us_id"].Value = us_id;

                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    usname = reader["LastName"].ToString() +" "+ reader["FirstName"].ToString();
                }
                cnn.Close();
            }
            catch (Exception ex)
            {
                Response.Write(" Lỗi ở Check User ID: " + ex);
                cnn.Close();
            }

            return usname;
        }


        //Bind data to drr:
        protected void BindDrr()
        {
            try
            {
                cnnString = ConfigurationManager.ConnectionStrings["DATNconnection"].ToString();
                cnn = new SqlConnection(cnnString);
                cnn.Open();

                string SearchQuery = "SELECT * FROM dbo.GroupCustomer WHERE Us_Id = @Us_Id";

                cmd = new SqlCommand(SearchQuery, cnn);

                cmd.Parameters.Add("@Us_Id", SqlDbType.Int);
                cmd.Parameters["@Us_Id"].Value = Convert.ToInt16(Session["Us_Id"]);

                SqlDataReader reader = cmd.ExecuteReader();

                //Group Khach hang:
                var GroupCS = new Dictionary<string, string>();
                GroupCS.Add("-1", "Chưa Chọn");

                int i = 0;
                while (reader.Read())
                {
                    i++;
                    GroupCS.Add(reader["GrCus_Id"].ToString(), reader["Name"].ToString());
                }

                ddr_GroupCS.DataTextField = "Value";
                ddr_GroupCS.DataValueField = "Key";
                ddr_GroupCS.DataSource = GroupCS;
                ddr_GroupCS.DataBind();

                //Check Nếu nhóm Group Rỗng:
                if (i == 0)
                {
                    lbCheckGroup.Text = "Bạn Chưa có Nhóm Khách Hàng!";
                }
                else
                {
                    //lbCheckGroup
                    lbCheckGroup.Text = "Hãy Chọn Nhóm Để Thêm khách Hàng Gửi!";
                }

                cnn.Close();
            }
            catch (Exception ex)
            {
                cnn.Close();
                Response.Write("Lỗi: " + ex);
            }
            finally
            {
                cnn.Close();
            }
        }

     
    }
}